<template>
  <div class="flex flex-col h-full p-4">
    <!-- 详情页面 -->
    <BatteryPackDetail v-if="showDetailsRef" :battery-id="detailId" @go-back="goBackToList" />

    <!-- 电池监控容器 -->
    <div v-else class="flex-1 flex flex-col bg-white rounded-lg shadow p-6 min-h-0">
      <!-- 顶部统计数字 -->
      <div class="mb-6">
        <div class="flex items-center text-lg font-bold mb-2 gap-2">
          <span>Total Battery Accounts</span>
          <CountUp :start-val="0" :end-val="pagination.total" :duration="2.5" :options="{ separator: ',' }" />
        </div>

        <!-- 筛选栏 -->
        <div class="flex items-center gap-4 mb-6">
          <el-input v-model="filters.batteryPackSN" placeholder="Battery Pack SN/Device SN" clearable class="w-70!" @keyup.enter="searchBatteries">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>

          <el-select v-model="filters.faultStatus" placeholder="All Fault Status" clearable class="w-36!">
            <el-option v-for="item in faultStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-select v-model="filters.batteryType" placeholder="All Battery Type" clearable class="w-36!">
            <el-option v-for="item in batteryTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <div class="flex ml-auto">
            <el-button type="default" @click="resetFilters">Reset</el-button>
            <el-button type="primary" @click="searchBatteries">Search</el-button>
          </div>
        </div>
      </div>

      <!-- 表格部分 -->
      <PageState :loading="loading" :error-message="errorMessage" :has-data="displayedBatteryList.length > 0" @retry="retryFetch">
        <BatteryPackTable :battery-data="displayedBatteryList" :pagination="pagination" @page-change="handleCurrentChange" @size-change="handleSizeChange" @detail="handleDetail" class="flex-1" />
      </PageState>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted, onDeactivated } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import CountUp from "vue-countup-v3";
import { faultStatusOptions, type BatteryPackItem } from "./data";
import { bmsApi } from "@/api/bms";
import BatteryPackTable from "./components/BatteryPackTable.vue";
import BatteryPackDetail from "./components/BatteryPackDetail.vue";
import PageState from "@/components/base/PageState.vue";

// 切换到详情页面
const showDetailsRef = ref(false);

// 详情页面id
const detailId = ref("");

// 定义筛选条件
const filters = reactive({
  batteryPackSN: "",
  faultStatus: "All fault status",
  batteryType: "All battery type"
});

// 分页控制
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 电池数据
const batteryPacks = ref<BatteryPackItem[]>([]);

// 动态电池类型选项
const batteryTypeOptions = ref([{ value: "All battery type", label: "All battery type" }]);

// 加载与错误态
const loading = ref(false);
const errorMessage = ref("");

// 当前页显示的电池数据（直接使用API返回的数据，不需要本地筛选）
const displayedBatteryList = computed(() => {
  return batteryPacks.value;
});

// 方法
// 获取电池类型选项（从API数据中提取）
const updateBatteryTypeOptions = (batteryList: BatteryPackItem[]) => {
  const uniqueTypes = new Set<string>();
  batteryList.forEach((item) => {
    if (item.batteryType) {
      uniqueTypes.add(item.batteryType);
    }
  });

  const typeOptions = Array.from(uniqueTypes).map((type) => ({
    value: type,
    label: type
  }));

  batteryTypeOptions.value = [{ value: "All battery type", label: "All battery type" }, ...typeOptions];
};

// 获取电池监控列表
const fetchBatteryList = async () => {
  loading.value = true;
  errorMessage.value = "";

  try {
    // 构建查询参数
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      faultStatus: filters.faultStatus !== "All fault status" ? filters.faultStatus : undefined,
      batteryType: filters.batteryType !== "All battery type" ? filters.batteryType : undefined
    };

    // 处理SN搜索：同时支持电池包SN和设备SN搜索
    if (filters.batteryPackSN) {
      const searchValue = filters.batteryPackSN.trim();
      // 根据API文档，可以同时传递两个参数，后端会进行OR查询
      params.sn = searchValue;
      params.sn = searchValue;
    }

    // 移除undefined值
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log("调用BMS API:", params);
    const response = await bmsApi.getPage(params);

    if (response.code === 0) {
      const data = response.data;
      batteryPacks.value = data.list || [];
      pagination.total = data.total || 0;

      // 更新电池类型选项
      updateBatteryTypeOptions(data.list || []);

      console.log("BMS列表数据获取成功:", data);
    } else {
      throw new Error(response.msg || "获取数据失败");
    }
  } catch (error: any) {
    console.error("获取BMS列表失败:", error);
    errorMessage.value = error.message || "网络请求失败，请重试";
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.batteryPackSN = "";
  filters.faultStatus = "All fault status";
  filters.batteryType = "All battery type";
  pagination.currentPage = 1;
  fetchBatteryList();
};

const searchBatteries = () => {
  // 搜索时重置分页
  pagination.currentPage = 1;
  fetchBatteryList();
};

// 移除防抖搜索功能，改为手动搜索模式

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  fetchBatteryList();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchBatteryList();
};

const handleDetail = (row: BatteryPackItem) => {
  console.log("handleDetail", row);
  // 跳转到详情页面
  detailId.value = row.batteryPackSN;
  showDetailsRef.value = true;
};

const goBackToList = () => {
  showDetailsRef.value = false;
  detailId.value = "";
};

// 重试获取数据
const retryFetch = () => {
  console.log("Retrying fetch...");
  errorMessage.value = "";
  fetchBatteryList();
};

// 组件挂载后获取数据
onMounted(() => {
  fetchBatteryList();
});

onDeactivated(() => {
  showDetailsRef.value = false;
  detailId.value = "";
});
</script>

<style lang="scss" scoped>
/* 电池监控页面样式 */
</style>
